<template>
  <div class="announcement-management">
    <!-- 搜索栏 -->
    <div class="search-input-group">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="公告标题">
          <el-input v-model="searchForm.announcementTitle" placeholder="请输入公告标题" style="width: 200px" />
        </el-form-item>
        <el-form-item label="公告类型">
          <el-input v-model="searchForm.announcementType" placeholder="请输入公告类型" style="width: 150px" />
        </el-form-item>
        <el-form-item label="公告内容">
          <el-input v-model="searchForm.announcementContent" placeholder="请输入公告内容" style="width: 300px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮组 -->
    <div class="btn-group">
      <el-button type="primary" :icon="Plus" @click="showAddDialog">添加</el-button>
      <el-button type="success" :icon="Edit" @click="showEditDialog" :disabled="multipleSelection.length !== 1">修改</el-button>
      <el-button type="danger" :icon="Delete" @click="handleDelete" :disabled="multipleSelection.length <= 0">删除</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="dataList"
      style="width: 100%"
      row-key="id"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="40" />
      <el-table-column type="index" label="序号" width="80" show-overflow-tooltip />
      <el-table-column prop="announcementTitle" label="公告标题" width="200" show-overflow-tooltip />
      <el-table-column prop="announcementType" label="公告类型" width="100" show-overflow-tooltip />
      <el-table-column prop="announcementContent" label="公告内容" show-overflow-tooltip />
      <el-table-column prop="dataStatus" label="公告状态" width="100" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.dataStatus === 1 ? '启用' : '禁用' }}
        </template>
      </el-table-column>
      <el-table-column prop="createBy" label="创建人" width="100" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip />
      <el-table-column prop="updateTime" label="更新时间" width="180" show-overflow-tooltip />
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/修改对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      class="announcement-dialog"
    >
      <el-form ref="announcementFormRef" :model="announcementForm" :rules="announcementRules" label-width="120px">
        <el-form-item label="公告标题" prop="announcementTitle">
          <el-input
            v-model="announcementForm.announcementTitle"
            placeholder="请输入公告标题"
            show-word-limit
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="公告类型" prop="announcementType">
          <el-input
            v-model="announcementForm.announcementType"
            placeholder="请输入公告类型"
            show-word-limit
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="公告状态" prop="dataStatus">
          <el-radio-group v-model="announcementForm.dataStatus">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公告内容" prop="announcementContent">
          <el-input
            v-model="announcementForm.announcementContent"
            type="textarea"
            placeholder="请输入公告内容"
            show-word-limit
            maxlength="2000"
            :rows="6"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAnnouncementForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAnnouncementList, searchAnnouncement, addAnnouncement, updateAnnouncement, deleteAnnouncement } from '@/api/management/announcement'

// 搜索表单
const searchForm = reactive({
  announcementTitle: '',
  announcementType: '',
  announcementContent: ''
})

// 数据列表
const dataList = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 多选数据
const multipleSelection = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加公告')
const announcementFormRef = ref()
const announcementForm = reactive({})
const announcementRules = {
  announcementTitle: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { max: 100, message: '公告标题不能超过100个字符', trigger: 'blur' }
  ],
  announcementType: [
    { required: true, message: '请输入公告类型', trigger: 'blur' },
    { max: 50, message: '公告类型不能超过50个字符', trigger: 'blur' }
  ],
  dataStatus: [
    { required: true, message: '请选择公告状态', trigger: 'change' }
  ],
  announcementContent: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { max: 2000, message: '公告内容不能超过2000个字符', trigger: 'blur' }
  ]
}

// 是否正在搜索
const isSearch = ref(false)

// 获取数据列表
const getDataList = async () => {
  try {
    const res = await getAnnouncementList(pagination.currentPage)
    if (res.code === 200) {
      dataList.value = res.data.records
      pagination.total = res.data.total
      pagination.pageSize = res.data.size
      pagination.currentPage = res.data.current
    }
  } catch (error) {
    console.error('获取公告列表失败:', error)
  }
}

// 搜索数据
const handleSearch = async () => {
  isSearch.value = true
  pagination.currentPage = 1
  try {
    const res = await searchAnnouncement(searchForm, pagination.currentPage)
    if (res.code === 200) {
      dataList.value = res.data.records
      pagination.total = res.data.total
      pagination.pageSize = res.data.size
      pagination.currentPage = res.data.current
    }
  } catch (error) {
    console.error('搜索公告失败:', error)
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.announcementTitle = ''
  searchForm.announcementType = ''
  searchForm.announcementContent = ''
  isSearch.value = false
  pagination.currentPage = 1
  getDataList()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加公告'
  // 清空表单
  announcementForm.id = undefined
  announcementForm.announcementTitle = ''
  announcementForm.announcementType = ''
  announcementForm.dataStatus = 1 // 默认启用
  announcementForm.announcementContent = ''
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = () => {
  if (multipleSelection.value.length !== 1) {
    ElMessage.warning('请选择一条数据进行编辑')
    return
  }
  dialogTitle.value = '修改公告'
  // 填充表单数据
  const selectedItem = multipleSelection.value[0]
  Object.assign(announcementForm, selectedItem)
  dialogVisible.value = true
}

// 提交表单
const submitAnnouncementForm = async () => {
  if (!announcementFormRef.value) return
  try {
    await announcementFormRef.value.validate()
    if (announcementForm.id) {
      // 修改操作
      await updateAnnouncement(announcementForm)
    } else {
      // 添加操作
      const addParams = {
        announcementTitle: announcementForm.announcementTitle,
        announcementType: announcementForm.announcementType,
        dataStatus: announcementForm.dataStatus,
        announcementContent: announcementForm.announcementContent
      }
      await addAnnouncement(addParams)
    }
    dialogVisible.value = false
    refreshList()
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

// 删除操作
const handleDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  const ids = multipleSelection.value.map(item => item.id)
  const deleteParams = { list: ids }
  
  await ElMessageBox.confirm(
    `确定要删除选中的 ${ids.length} 条数据吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteAnnouncement(deleteParams)
      refreshList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  refreshList()
}

// 处理当前页变化
const handleCurrentChange = (current) => {
  pagination.currentPage = current
  refreshList()
}

// 刷新列表
const refreshList = () => {
  if (isSearch.value) {
    handleSearch()
  } else {
    getDataList()
  }
}

// 页面加载时获取数据
onMounted(() => {
  getDataList()
})
</script>

<style scoped>
.announcement-management {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.search-input-group {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-input-group .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}

.btn-group {
  margin-bottom: 15px;
}

.btn-group .el-button {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.announcement-dialog {
  .el-input__inner {
    width: 100%;
  }
}
</style>